﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Network;

public class TestNetwork : MonoBehaviour
{
	// multiplayer
	public string localIp;
	public int port = 5004;
	public string selfName;
	public string opponentName;
	BroadcastServer broadcastServer;
	BroadcastClient broadcastClient;
	INetwork network;

	public Button serverButton;
	public Button clientButton;

	private void OnApplicationQuit()
	{
		if (network != null && network.IsConnected())
		{
			network.Close();
			if (network.IsHost())
			{
				Debug.Log("服务器断开连接");
			}
			else
			{
				Debug.Log("客户端断开连接");
			}
			network = null;
		}
	}

	// Start is called before the first frame update
	void Start()
	{
		localIp = NetworkUtils.GetLocalIpAddress("InterNetwork")[0];

		if (serverButton != null) serverButton.onClick.AddListener(() => { SetAsHost(); });
		if (clientButton != null) clientButton.onClick.AddListener(() => { FindingHost(); });
	}

	private void OnEnable()
	{
		//client.onReceive = OnMessageReceive;
	}

	private void OnDisable()
	{
		//client.onReceive = null;
	}

	// Update is called once per frame
	void Update()
	{

	}

	// 网络消息接收回调
	void OnMessageReceive(string msg)
	{
		Debug.Log("收到消息: " + msg);
	}

	// 作为主机开始udp广播ip
	void SetAsHost()
	{
		string data = $"testNetwork,{localIp},{selfName}";
		broadcastServer = new BroadcastServer(port);
		broadcastServer.StartBroadcasting(data);
		Debug.Log("开始广播");
		network = new GameServer(localIp, port);
		network.StartConnect();
		network.RegistConnectedCallback(OnConnected);
		network.RegistReceiveCallback(OnMessageReceive);
	}

	void EndBroadcast()
	{
		if (broadcastServer.broadcasting)
		{
			network?.Close();
			network = null;
			broadcastServer.Close();
		}
	}

	// 作为客机开始监听udp广播
	void FindingHost()
	{
		broadcastClient = new BroadcastClient(port, ReceiveBroadcastCallback);
		broadcastClient.StartListening();
	}

	// 作为客机结束监听广播
	void StopFindingHost()
	{
		if (broadcastClient.listening)
		{
			network?.Close();
			network = null;
			broadcastClient.Close();
		}
	}

	// 作为客机接收到udp广播的回调
	void ReceiveBroadcastCallback(string data)
	{
		if (data.StartsWith("testNetwork"))
		{
			Debug.Log("收到广播");
			string[] split = data.Split(',');
			opponentName = split[2];
			network = new GameClient(split[1], port);
			network.RegistConnectedCallback(OnConnected);
			network.RegistReceiveCallback(OnMessageReceive);
			network.StartConnect();
		}
	}

	void OnConnected()
	{
		if (network.IsHost())
		{
			Debug.Log("服务器连接");
			broadcastServer.Close();
			broadcastServer = null;
			network.SendMessage("i am a server send");
		}
		else
		{
			Debug.Log("客户端连接");
			broadcastClient.Close();
			broadcastClient = null;
			network.SendMessage("i am a client send");
		}
	}
}
